#!/usr/bin/python
#-*-coding: utf-8-*-
import sys, os
import socket
from collections import namedtuple

Address = namedtuple('Address', ['ip', 'port'])
# Klasse Address ist ein namedtuple

def get_text_lines(dat='gedicht.txt'):
    """Gibt Dateiinhalt als Liste von Zeilen zurueck"""
    if not os.path.exists('/'.join([os.getcwd(), dat])):
        raise IOError, 'Die Datei %s wurde nicht gefunden' % dat
    text_lines = [line for line in file(dat)]
    return text_lines

def send_msg(destination_ip, destination_port, text_lines=['bla\n']):
    """Versendet msg an Zieladresse"""

    destination_address = Address(destination_ip, destination_port)    
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # Adressfamilie, Soket-Typ, Protokoll (automatisch durch Typ) default 0
    # socket([family[, type[, protokoll]]]) -> socket object
    print 'versende jetzt, da UDP hab ich keine Rueckmeldung obs ankommt ...'
    for line in text_lines:
        sock.sendto(line, destination_address)
        # sendto(data[, flags], addr) -- send data to a given address

    sock.close()
            
if __name__ == '__main__':
    port = 1111
    ip = 'localhost'
    dat_poem = 'gedicht_lang.txt'
    text_lines = ['example text\n', 'blalsdl\n']

    if len(sys.argv) == 3:
        ip, dat_poem = sys.argv[1], sys.argv[2]
    print 'Sende an %s die Datei %s' % (ip, dat_poem)
    text_lines = get_text_lines(dat_poem)
    send_msg(ip, port, text_lines)
    
